from flask import Flask, request, render_template,render_template_string, jsonify
from flask_socketio import SocketIO, emit
import json
import haiyi
import logging
from datetime import datetime
from logging.handlers import RotatingFileHandler

app = Flask(__name__)
socketio = SocketIO(app)

# 配置日志
current_date = datetime.now().strftime('%Y-%m-%d')
handler = RotatingFileHandler(f'/home/linaro/log/haiyi_app_{current_date}.log', maxBytes=10*1024*1024, backupCount=3)
handler.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
handler.setFormatter(formatter)
app.logger.addHandler(handler)
app.logger.setLevel(logging.DEBUG)  # 确保应用本身的日志级别也设置为 DEBUG


@socketio.on('connect')
def on_connect():
    app.logger.info('SokcetIOClient connected')
    emit('message', {'data': '回调显示区域'})

@socketio.on('disconnect')
def on_disconnect():
    app.logger.info('SokcetIOClient disconnected')

@app.route('/create/notify', methods=['GET', 'POST'])
def order_notify():
    data = request.get_json()
    if not data.get("data"):
        return jsonify({"code": "20001", "message": "Invalid JSON"}), 400
    msg =  haiyi.decrypt(data["data"])
    socketio.emit('message', {'data': msg})
    app.logger.info(msg)

    response_data = {
        "code": "00000",
        "message": "success"
    }
    return jsonify(response_data)

@app.route('/open')
def page_open():
    app.logger.info("open page")
    return render_template('open.html')

@app.route('/shopping', methods=['POST'])
def order_shopping():
    app.logger.info("shopping")
    # 这里可以添加你想要执行的后端逻辑
    func, path, detail = haiyi.haiyi_post_dict.get("post_ordercreate")
    post_data, result = func(path, "SHOPPING")
    app.logger.info(f"POST: {post_data}")
    app.logger.info(f"RESULT: {result}")
    return jsonify(result)

@app.route('/operator', methods=['POST'])
def order_operator():
    app.logger.info("operator")
    # 这里可以添加你想要执行的后端逻辑
    func, path, detail = haiyi.haiyi_post_dict.get("post_ordercreate")
    post_data, result = func(path)
    app.logger.info(f"POST: {post_data}")
    app.logger.info(f"RESULT: {result}")
    return jsonify(result)

@app.route('/decrypt', methods=['POST'])
def decrypt():
    data = request.get_json()
    if data.get("data"):
        return haiyi.decrypt(data["data"])
    return jsonify({"error": "Invalid JSON"}), 400

def json_save(file_path, jdata):
    with open(file_path,'w',encoding='utf-8') as f:
        json.dump(jdata, f,ensure_ascii=False)

@app.route('/', methods=['GET', 'POST'])
def index():
    result = None
    post_data = None
    order_video = None
    if request.method == 'POST':
        action = request.form.get('action')
        json_data = request.form.get('json_data')
        kfunc = haiyi.haiyi_post_dict.get(action)
        if kfunc:
            post_data, result = kfunc[0](kfunc[1])
            json_save(f"{action}.json", result)
            post_data = kfunc[1] + ":\r\n" + post_data
        else:
            try:
                data = json.loads(json_data)
                if action == 'gen_haiyi_value':
                    result = process_data(data)
                elif action == 'post_haiyi':
                    url = request.form.get('url')
                    post_data, result = haiyi.post_format(data, url)
            except json.JSONDecodeError as e:
                result = f"Error: Invalid JSON - {str(e)}"
        get_order_no = request.form.get('order_no')
        if get_order_no:
            post_data, order_video = haiyi.post_ordervideo_func(get_order_no)

    return render_template('index.html'
                            , post_data=post_data
                            , result=result
                            , order_video=order_video
                            , buttons=haiyi.haiyi_post_dict)

def process_data(data):
    signature, data_str = haiyi.generate_msg(data)
    result = "Authorization:" + signature + "\r\n" + data_str
    return result

import subprocess
import time

def is_time_synchronized():
    try:
        # 检查ntp服务状态或使用其他方法确认时间是否已同步
        # 这里我们简单地尝试运行`ntpq -p`命令来查看是否有有效的NTP服务器
        result = subprocess.run(['ntpq', '-p'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
        if result.returncode == 0 and "*" in result.stdout:  # 检查是否有行以'* '开头，表示有一个首选的同步源
            return True
        else:
            return False
    except Exception as e:
        print(f"Error checking NTP synchronization status: {e}")
        return False

def wait_for_time_sync(timeout=60):
    start_time = time.time()
    while not is_time_synchronized():
        elapsed_time = time.time() - start_time
        if elapsed_time > timeout:
            print("Timed out waiting for time synchronization.")
            return False
        print("Waiting for system time to be synchronized with NTP server...")
        time.sleep(5)  # 等待一段时间后再次检查
    print("System time has been synchronized.")
    return True


if __name__ == '__main__':
    # 尝试与NTP服务器同步时间
    try:
        subprocess.run(['sudo', 'ntpdate', '-u', 'pool.ntp.org'], check=True)
    except subprocess.CalledProcessError as e:
        print(f"Failed to update system time: {e}")

    # 循环等待直到时间同步完成
    if wait_for_time_sync():
        # 在这里放置你想要执行的代码
        print("Proceeding with the main program logic after time sync...")
        # ...
    else:
        print("Failed to proceed due to time sync failure.")

    #app.run(debug=True, host='0.0.0.0', port=8000)
    from gevent import pywsgi
    from haiyi_app import app
    server = pywsgi.WSGIServer(('0.0.0.0', 8000), app)
    server.serve_forever()
